<template>
  <scroll-view scroll-y class="page-home flex" enable-flex @scroll="scroll">
    <view class="container">
      <view :style="{ height: `${safeAreaInsets?.top + 50}px` }" />
      <view
        class="top-bg fixed top-0 z-10 w-full bg-red text-center"
        :style="{ height: `${40}px`, paddingTop: `${safeAreaInsets?.top}px`, lineHeight: '40px', opacity: navbarOpacity }"
      />
      <image
        class="task-pic" src="https://mp-faaaa8a0-2641-45b8-8dbc-bcb0d1463eb4.cdn.bspapp.com/app/home-task.png"
        mode="aspectFit"
      />

      <view class="card">
        <view class="name" @click="showMore">
          你好,{{ selectedChild?.name }}
          <More />
        </view>
        <view class="tips">
          我的积分 {{ selectedChild?.score || 0 }}
        </view>
        <image
          class="card-pic" src="https://mp-faaaa8a0-2641-45b8-8dbc-bcb0d1463eb4.cdn.bspapp.com/app/girl.png"
          mode="aspectFit"
        />
      </view>

      <view class="tasks-list">
        <Title class="tasks-title" title="每日任务" />
        <view class="task-container">
          <HomeTaskItem v-for="task in dayTasks" :key="task.taskId" :item="task" :child-id="selectedChild.id" @change-status="changeStatus(task)" />
        </view>
        <Title title="每周任务" />
        <view class="task-container">
          <HomeTaskItem v-for="task in weekTasks" :key="task.taskId" :item="task" :child-id="selectedChild.id" @change-status="changeStatus(task)" />
        </view>
      </view>

      <view class="empty-block" />
    </view>
  </scroll-view>
  <SheetCom v-model="show" title="选择子女" @submit="submitSelectChild" @close="reset">
    <view v-for="item in childLists" :key="item.id" class="child-item" :class="[item.id === userSelectedChild.id && 'active']" @click="clickChild(item)">
      {{ item.name }}
    </view>
  </SheetCom>
</template>

<script lang="ts" setup>
import type { IChildInfo } from '@/api/child'
import type { ITodayTask } from '@/api/task'
import { deepClone } from '@alova/shared'
import { storeToRefs } from 'pinia'
import { generateDailyTasks, TaskStatus, TaskType } from '@/api/task'
import HomeTaskItem from '@/components/HomeTaskItem.vue'
import More from '@/components/More.vue'
import SheetCom from '@/components/Sheet.vue'
import Title from '@/components/Title.vue'
import { useTokenStore } from '@/store'
import { useChildStore } from '@/store/child'
import { safeAreaInsets } from '@/utils/systemInfo'

defineOptions({
  name: 'Home',
})

const show = ref(false)
const userSelectedChild = ref<IChildInfo>({} as IChildInfo)
// 控制导航栏透明度
const navbarOpacity = ref(0)
const todayTask = ref<ITodayTask[]>([])

definePage({
  // 使用 type: "home" 属性设置首页，其他页面不需要设置，默认为page
  // type: 'home',
  style: {
    // 'custom' 表示开启自定义导航栏，默认 'default'
    navigationStyle: 'custom',
    navigationBarTitleText: '首页',
  },
})

// #region Props
// #endregion
// #region Emits
// #endregion
// #region Hooks
const childStore = useChildStore()
const tokenStore = useTokenStore()
const { childLists, selectedChild } = storeToRefs(childStore)
const { token } = storeToRefs(tokenStore)
// #endregion
// #region Computed
const dayTasks = computed(() => {
  return todayTask.value?.filter(item => item.taskType === TaskType.Day)
})
const weekTasks = computed(() => {
  return todayTask.value?.filter(item => item.taskType === TaskType.Week)
})
// #endregion
// #region Watch
// #endregion
// #region Event
// #endregion
// #region Function
function changeStatus(item: ITodayTask) {
  todayTask.value.forEach((task) => {
    if (task.taskId === item.taskId) {
      task.status = task.status === TaskStatus.Complete ? TaskStatus.Pending : TaskStatus.Complete
    }
  })
  childStore.fetchChildList()
}

function showMore() {
  show.value = true
  userSelectedChild.value = deepClone(selectedChild.value)
}

function clickChild(item: IChildInfo) {
  userSelectedChild.value = deepClone(item)
}

function reset() {
  userSelectedChild.value = {} as IChildInfo
  show.value = false
}

function submitSelectChild(cb: () => void) {
  if (selectedChild.value.id !== userSelectedChild.value.id) {
    childStore.toggleSelectedChild(userSelectedChild.value)
    fetchDailyTask()
  }
  reset()
  cb()
}

function fetchDailyTask() {
  generateDailyTasks({ childId: selectedChild.value?.id }).then((res) => {
    console.log('res', res)
    todayTask.value = res
  })
}

function scroll(e) {
  const scrollTop = e.detail.scrollTop

  const threshold = 10
  if (scrollTop > threshold) {
    // 计算透明度：从 0 到 1 渐变显示
    navbarOpacity.value = Math.min(1, (scrollTop - threshold) / 50)
  }
  else {
    navbarOpacity.value = 0
  }
}
// #endregion
// #region Life Cycle
onShow(async () => {
  if (!token.value) {
    await useTokenStore().wxLogin()
  }
  await childStore.fetchChildList()
  fetchDailyTask()
})
// #endregion
// #region Expose
// #endregion
</script>

<style lang="scss">
.page-home {
  background: url('https://mp-faaaa8a0-2641-45b8-8dbc-bcb0d1463eb4.cdn.bspapp.com/app/home-bg.jpg') no-repeat;
  background-size: cover;
  height: 100%;
  flex-direction: column;
  box-sizing: border-box;
  overflow-y: scroll;

  .top-bg {
    backdrop-filter: blur(20px);
    -webkit-backdrop-filter: blur(20px);
    /* 兼容 Safari */
    background-color: rgba(255, 255, 255, 0.25);
    transition: opacity 0.3s ease;
    /* 平滑过渡效果 */
    font-size: 25rpx;
  }

  .empty-block {
    height: calc(env(safe-area-inset-bottom) + 70px);
  }

  .task-pic {
    width: 153px;
    height: 52px;
    margin: 0 18px 10px 18px;
  }

  .card {
    height: 110px;
    border-radius: 20px;
    background: linear-gradient(to bottom, #e2fc29, #f8f49a);
    border: 2px solid rgba($color: #fff, $alpha: 0.8);
    margin: 0 18px;
    position: relative;
    display: flex;
    flex-direction: column;
    justify-content: center;

    .card-pic {
      width: 105px;
      height: 161px;
      position: absolute;
      right: 16px;
      bottom: 5px;
    }

    .name {
      color: var(--main-color);
      font-weight: 600;
      font-size: 24px;
      margin-bottom: 20px;
      padding-left: 16px;
      display: flex;
      align-items: center;

      image {
        margin-left: 8px;
      }
    }

    .tips {
      color: var(--text-color);
      opacity: 0.5;
      font-size: 14px;
      padding-left: 16px;
    }
  }

  .tasks-list {
    padding: 0 18px;

    .ui-title {
      padding: 20px 0;
    }

    .task-container {
      display: flex;
      flex-direction: column;
      gap: 20px;
    }
  }
}
.child-item {
  height: 70px;
  background: var(--card-bg-color);
  border-radius: 10px;
  display: flex;
  align-items: center;
  padding: 0 20px;
  box-sizing: border-box;
  color: var(--main-color);
  border: 2px solid var(--card-bg-color);
  &.active {
    border: 2px solid var(--main-light-color);
  }
}
</style>
